﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace YArchitech.LIB
{
	public static class IniHelper
	{
		[DllImport("kernel32")]
		private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

		public static void WriteSetting(string section, string key, string value, string filePath)
		{
			IniHelper.WritePrivateProfileString(section, key, value, filePath);
		}

		public static void WriteSetting(string section, string key, int value, string filePath)
		{
			IniHelper.WritePrivateProfileString(section, key, value.ToString(), filePath);
		}

		public static void WriteSetting(string section, string key, double value, string filePath)
		{
			IniHelper.WritePrivateProfileString(section, key, value.ToString(), filePath);
		}

		[DllImport("kernel32")]
		private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

		public static string GetSetting(string Section, string Key, string filePath, string valueDef = "")
		{
			if (!File.Exists(filePath))
			{
				return valueDef;
			}
			int num = 12288;
			string result = valueDef;
			StringBuilder stringBuilder = new StringBuilder(num);
			if (IniHelper.GetPrivateProfileString(Section, Key, "", stringBuilder, num, filePath) != 0)
			{
				result = stringBuilder.ToString();
			}
			return result;
		}

		public static int GetIntSetting(string Section, string Key, string ConfigFile, int valueDef = 0)
		{
			string text = valueDef.ToString();
			text = IniHelper.GetSetting(Section, Key, ConfigFile, text);
			int result = valueDef;
			int.TryParse(text, out result);
			return result;
		}

		public static double GetDoubleSetting(string Section, string Key, string ConfigFile, double valueDef = 0.0)
		{
			string text = valueDef.ToString();
			text = IniHelper.GetSetting(Section, Key, ConfigFile, text);
			double result = valueDef;
			double.TryParse(text, out result);
			return result;
		}
	}
}
